package com.starhub.application.collection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.service.KnowledgeCollectionService;
import com.starhub.application.collection.service.KnowledgeItemService;
import com.starhub.domain.knowledge.dto.QueryKnowledgeItemDto;
import com.starhub.domain.knowledge.entity.KnowledgeItem;
import com.starhub.domain.knowledge.mapper.KnowledgeItemMapper;
import com.starhub.domain.knowledge.result.KnowledgeItemsSearchResult;
import com.starhub.domain.knowledge.vo.KnowledgeItemVo;
import com.starhub.utils.HubBeanUtils;
import com.starhub.utils.Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 知识库表服务实现类
 * @version: V1.0
 * @author: luosw
 * @time 2025-06-20
 */
@Service
public class KnowledgeItemServiceImpl implements KnowledgeItemService {

    private final KnowledgeItemMapper knowledgeItemMapper;

    public KnowledgeItemServiceImpl(KnowledgeItemMapper knowledgeItemMapper) {
        this.knowledgeItemMapper = knowledgeItemMapper;
    }

    @Autowired
    private KnowledgeCollectionService knowledgeCollectionService;

    @Override
    public int insert(KnowledgeItem knowledgeItem) {
        return knowledgeItemMapper.insert(knowledgeItem);
    }

    @Override
    public int updateById(KnowledgeItem knowledgeItem) {
        return knowledgeItemMapper.updateById(knowledgeItem);
    }


    @Override
    public KnowledgeItem selectById(Long id) {
        return knowledgeItemMapper.selectById(id);
    }

    @Override
    public KnowledgeItem selectByIdAndNotDeleted(Long id) {
        LambdaQueryWrapper<KnowledgeItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeItem::getId, id)
                .eq(KnowledgeItem::getDeleteType, 0);
        return knowledgeItemMapper.selectOne(queryWrapper);
    }


    @Override
    public int deleteById(Long id) {

        KnowledgeItem knowledgeItem = new KnowledgeItem();
        knowledgeItem.setDeleteType(1);
        knowledgeItem.setId(id);
        return knowledgeItemMapper.updateById(knowledgeItem);
    }


    @Override
    public int deleteRecord(Long id) {
        return knowledgeItemMapper.deleteById(id);
    }

    @Override
    public List<KnowledgeItem> selectByMap(Map<String, Object> params) {

        String baseId = Util.null2String(params.get("baseId"));
        String collectionId = Util.null2String(params.get("collectionId"));
        Map<String, Object> columnMap = new HashMap<>();
        if(StringUtils.isNotEmpty(baseId)){
            columnMap.put("base_id",baseId);
        }
        if(StringUtils.isNotEmpty(collectionId)){
            columnMap.put("collection_id",collectionId);
        }
        columnMap.put("delete_type",0);
        return knowledgeItemMapper.selectByMap(columnMap);
    }


    @Override
    public List<KnowledgeItem> getActiveKnowledgeItem(Map<String, Object> params) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("delete_type",0);
        return knowledgeItemMapper.selectByMap(columnMap);
    }

    @Override
    public List<String> getAllDatas(Long collectionId) {
        KnowledgeCollection knowledgeCollection = knowledgeCollectionService.selectById(collectionId);
        if(knowledgeCollection == null){
            return null;
        }
        
        List<KnowledgeItem> knowledgeItems = knowledgeItemMapper.selectList(new LambdaQueryWrapper<KnowledgeItem>()
            .eq(KnowledgeItem::getCollectionId, collectionId)
            .eq(KnowledgeItem::getDeleteType, 0));
        return knowledgeItems.stream().map(KnowledgeItem::getContent).collect(Collectors.toList());
    }

    @Override
    public KnowledgeItemsSearchResult pageKnowledgeItems(QueryKnowledgeItemDto queryDto, Long pageNo, Long pageSize) {
        // 创建分页对象
        Page<KnowledgeItem> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<KnowledgeItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeItem::getCollectionId, queryDto.getCollectionId())
                    .eq(KnowledgeItem::getDeleteType, 0); // 未删除的记录

        // 如果有关键词，添加内容模糊搜索条件
        if (!Util.isEmpty(queryDto.getKeyword())) {
            queryWrapper.and((query) ->query.like(KnowledgeItem::getContent, queryDto.getKeyword())
                        .or()
                    .like(KnowledgeItem::getTitle, queryDto.getKeyword()));
        }

        // 如果有是否已向量化，添加向量化搜索条件
        if (!Util.isEmpty(queryDto.getIsEmbedded())) {
            queryWrapper.eq(KnowledgeItem::getIsEmbedded, queryDto.getIsEmbedded());
        }

        // 按创建时间倒序排序
        queryWrapper.orderByDesc(KnowledgeItem::getCreateTime);

        // 执行分页查询
        Page<KnowledgeItem> resultPage = knowledgeItemMapper.selectPage(page, queryWrapper);

        // 转换
        List<KnowledgeItemVo> result = page.getRecords().stream()
                                           .map(item -> {
                                               KnowledgeItemVo vo = HubBeanUtils.convert(item, KnowledgeItemVo.class);
                                               vo.setIsEmbedded(Util.equals(item.getIsEmbedded(), 1));
                                               return vo;
                                           })
                                           .toList();

        return KnowledgeItemsSearchResult.success(result, resultPage.getTotal(), resultPage.getSize(),
                resultPage.getCurrent());
    }
} 